<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Auth\Guard;
use Illuminate\Http\Request;
use Auth;
class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }
    public function getLogin(){

    }
    public function postLogin(Request $request,Guard $auth)
    {
    	$credentials = $request->only('username', 'password');
    	$validator=self::validator($credentials);
    	if ($validator->fails()){
    		$messages = $validator->messages();
    		$show_warning = $messages->first();
    		return  	AjaxCallbackMessage($show_warning,false,URL('/'));
    	}
    	$user=User::where('username', trim($credentials['username']))->first();
    	if(isset($user->id) && $user->id && $user->password==md5($credentials['password'])){
    		User::loginSuccess($user);
    		return  	AjaxCallbackMessage('登陆成功',true,URL('home?submodule_id=4'));
    	}else{
    		return 	AjaxCallbackMessage('账号或密码错误',false, URL('auth/login'));
    	}
    }
    public function getLogout(){
    	if(Auth::check()){
    		Auth::logout();
    	}
    	return redirect('/');
    }
    
    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'username' => 'required|max:255',
            'password' => 'required|min:6'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}
